package com.lzx.iteam;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.*;
import com.lzx.iteam.bean.TalkListData;
import com.lzx.iteam.net.AsynHttpClient;
import com.lzx.iteam.net.CcMsgStructure;
import com.lzx.iteam.net.LocalLogin;
import com.lzx.iteam.util.*;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by zhangshuai on 15-4-9.
 */
public class FeedActivity extends Activity implements View.OnClickListener {

    private LinearLayout mBack;
    private RelativeLayout mLayout;
    private EditText mText, mEmail;
    private TextView mTvTitle,mSend;

    private ArrayList<String> nameCard;
    private PreferenceUtil mPreferenceUtil;

    /**
     * 0: 默认问题反馈
     * 1: 考勤故障反馈
     */
    private int mAction;
    private String mAttendanceId;

    private final int GET_USER_FEED = 1000;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case GET_USER_FEED:
                    if (msg.arg1 == 0) {
                        if ((!StringUtil.isEmpty(mEmail.getText().toString().trim())) && PhoneNumberArea.isEmail(mEmail.getText().toString().trim())) {
                            nameCard.set(5, mEmail.getText().toString().trim());
                            mPreferenceUtil.saveCloudContact(Constants.CONTACT_NAME_CARD, nameCard);
                        }
                        Toast.makeText(FeedActivity.this,"反馈提交成功",Toast.LENGTH_LONG).show();
                        finish();
                    }else{
                        Toast.makeText(FeedActivity.this,"您的反馈未提交成功，请重试",Toast.LENGTH_LONG).show();
                    }
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.feed_layout);
        Intent intent = getIntent();
        mAction = intent.getIntExtra("action",0);
        mAttendanceId = intent.getStringExtra("attendance_id");
        initView();
    }

    public void initView() {
        mBack = (LinearLayout) findViewById(R.id.feed_ll_back);
        mBack.setOnClickListener(this);
        mTvTitle = (TextView) findViewById(R.id.tv_feed_title);
        mSend = (TextView) findViewById(R.id.feed_tv_send);
        mSend.setOnClickListener(this);
        mText = (EditText) findViewById(R.id.feed_et_text);
        mEmail = (EditText) findViewById(R.id.feed_et_email_text);
        mLayout = (RelativeLayout) findViewById(R.id.feed_ll_context);
        mLayout.setOnClickListener(this);
        mPreferenceUtil = PreferenceUtil.getInstance(this);
        nameCard = (ArrayList<String>) mPreferenceUtil.getCloudContact(Constants.CONTACT_NAME_CARD);
        if (nameCard != null && nameCard.size() > 0) {
            if (!StringUtil.isEmpty(nameCard.get(5))) {
                mEmail.setText(nameCard.get(5));
            }
        }

        if (mAction == 0){

        }else if (mAction == 1){
            mTvTitle.setText("故障反馈");
            mText.setHint("请输入故障现象...");
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.feed_ll_back:
                finish();
                break;
            case R.id.feed_tv_send:
                if(StringUtil.isEmpty(mText.getText().toString().trim())){
                    Toast.makeText(this, "请填写内容", Toast.LENGTH_SHORT).show();
                }else{
                sendMessage();}

                break;
            case R.id.feed_ll_context:
                try {
                    ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                break;
        }
    }

    public void sendMessage() {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin.getInstance().mSid));
        if (mAction == 0){
            nvps.add(new BasicNameValuePair("context", mText.getText().toString().trim()));
        }else if (mAction == 1){
            nvps.add(new BasicNameValuePair("context", mText.getText().toString().trim() + "\n" + mAttendanceId));
        }
        if ((!StringUtil.isEmpty(mEmail.getText().toString().trim())) && PhoneNumberArea.isEmail(mEmail.getText().toString().trim())) {
            nvps.add(new BasicNameValuePair("email", mEmail.getText().toString().trim()));
        }
        FeedMessage message = new FeedMessage(mHandler.obtainMessage(GET_USER_FEED));
        message.mApi = AsynHttpClient.API_USER_FEED;
        message.mParams = nvps;
        AsynHttpClient.getInstance(this).execUserHttp(message);

    }

    class FeedMessage extends CcMsgStructure {
        private Message mmCallback;

        public FeedMessage(Message callback) {
            mmCallback = callback;
        }

        @Override
        public void onReceive(JSONObject data) {
            try {
                JSONObject jsonObject = data.getJSONObject(AsynHttpClient.KEY_CC_DATA);
            } catch (JSONException e) {
                e.printStackTrace();
            }


            if (mmCallback != null) {
                mmCallback.arg1 = 0;
                mmCallback.sendToTarget();
                return;
            }
        }

        @Override
        public void onError(int error, Object ret) {
            String errorMsg = null;
            if (ret != null) {
                JSONObject jData = null;
                try {
                    jData = new JSONObject(ret.toString());
                    errorMsg = jData.getString("msg");
                } catch (JSONException e) {
                    errorMsg = "服务端数据解析失败!";
                    e.printStackTrace();
                }

            }
            if (mmCallback != null) {
                mmCallback.arg1 = error;
                if (!StringUtil.isEmpty(errorMsg)) {
                    mmCallback.obj = errorMsg;
                } else {
                    mmCallback.obj = Constants.NETWORK_WRROR;
                }
                mmCallback.sendToTarget();
            }
        }
    }
}
